<template>
  <div class="relevance-order-list-dialog-wrap">
    <el-dialog
      v-loading="loading"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :show-close="true"
      :append-to-body="true"
      :fullscreen="false"
      :class="{ 'relevance-order-mobile-dialog': showMobilePage }"
      class="global-common-dialog relevance-order-common-dialog large-common-dialog-size"
      @close="closeDialog"
      @open="openDialog"
      @opened="opened"
    >
      <Title title="订单关联编辑" font-size="16px" style="margin: 0 0 24px"/>
      <div class="list-tab-relative">
        <div class="list-tab-absolute">
          <ListTab v-model="tabIndex" :tabs="tabs" :is-center="true" padding-left="0px"/>
        </div>
      </div>
      <el-form v-show="tabIndex === 0" :inline="!showMobilePage" :model="queryForm" :class="{'mobile-el-form': showMobilePage}" label-position="left">
        <el-form-item label="账号" label-width="70px">
          <el-input v-model="queryForm.resourceName" clearable size="small" placeholder="请输入内容" class="input-width-select" />
        </el-form-item>
        <el-form-item label="订单号" label-width="70px">
          <el-input v-model="queryForm.orderId" clearable size="small" placeholder="请输入内容" class="input-width-select" />
        </el-form-item>
        <el-form-item label="下单日期" label-width="70px">
          <el-date-picker
            v-model="dateTime"
            :unlink-panels="true"
            :clearable="true"
            :editable="false"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="timestamp"
            format="yyyy/MM/dd"
            size="small"
            @change="datePickerTime" />
        </el-form-item>
        <el-form-item label="含税金额" label-width="70px">
          <el-input
            :value="queryForm.taxAmount"
            type="text"
            size="small"
            clearable
            placeholder="请输入内容"
            class="input-width-select"
            @input="keyupEvent"
          />
        </el-form-item>
        <el-form-item label="品牌名称" label-width="70px">
          <el-input v-model="queryForm.theme" clearable size="small" placeholder="请输入内容" class="input-width-select" />
        </el-form-item>
        <div class="query-button">
          <el-button
            class="search-btn-style"
            type="primary"
            size="small"
            style="margin-right: 6px"
            plain
            @click="queryClick"
          >查询</el-button>
          <clear-btn @click="queryEmpty" />
        </div>
      </el-form>
      <div v-loading="orderListLoading" v-show="tabIndex === 0" class="total-table-list">
        <!-- v-if="orderList.items.length > 0" -->
        <el-table
          ref="resourceTable"
          :data="orderList.items"
          :max-height="showMobilePage ? '160px' : '338px'"
          class="table-fixed"
          row-key="id"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
        >
          <el-table-column :render-header="renderHeader" :width="40" label="" >
            <template slot-scope="scope">
              <el-checkbox :value="isChecked(scope.row.id)" @change="checkboxClick($event, scope.row)"/>
            </template>
          </el-table-column>
          <el-table-column label="订单号" width="220">
            <template slot-scope="scope">
              <router-link
                v-if="hasRouteAuth('crm:orderList:clientInfo')"
                :to="{name: 'orderDetail', params: { orderId: scope.row.id }}"
                target="_blank"
                class="original-order"
              >{{ scope.row.orderId || '--' }}</router-link>
              <span v-else>{{ scope.row.orderId || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="下单日期" width="120">
            <template slot-scope="scope">
              {{ scope.row.orderTime | standardFormatNoHour }}
            </template>
          </el-table-column>
          <el-table-column label="客户联系人">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.clientName" />
            </template>
          </el-table-column>
          <el-table-column label="账号">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.resourceName" />
            </template>
          </el-table-column>
          <el-table-column label="含税金额" width="120" align="right">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.taxAmount" :price="scope.row.taxAmount / 100" />
            </template>
          </el-table-column>
          <el-table-column label="品牌名称">
            <template slot-scope="scope">
              {{ scope.row.theme || '--' }}
            </template>
          </el-table-column>
        </el-table>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <el-pagination
            v-if="orderList.items.length > 0"
            :current-page.sync="orderList.page"
            :page-size="orderList.perPage"
            :total="orderList.total"
            :small="true"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            class="relevance-pagination"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <div v-else class="pagination-area">
          <el-pagination
            v-if="orderList.items.length > 0"
            :current-page="orderList.page"
            :page-size="orderList.perPage"
            :total="orderList.total"
            :pager-count="5"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes,jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <div v-if="orderList.items.length === 0" style="position: relative; top: -64px; z-index: 2">
          <empty-placeholder />
        </div>
      </div>
      <div v-show="tabIndex === 1" class="total-table-list">
        <el-table
          v-if="selectOrders.length > 0"
          ref="selectedTable"
          :data="selectOrders"
          :max-height="showMobilePage ? '160px' : '338px'"
          class="table-fixed"
          row-key="id"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
        >
          <el-table-column :width="40" label="" >
            <template slot-scope="scope">
              <el-checkbox :value="isChecked(scope.row.id)" @change="checkboxClick($event, scope.row)"/>
            </template>
          </el-table-column>
          <el-table-column label="订单号" width="220">
            <template slot-scope="scope">
              <router-link
                v-if="hasRouteAuth('crm:orderList:clientInfo')"
                :to="{name: 'orderDetail', params: { orderId: scope.row.id }}"
                target="_blank"
                class="original-order"
              >{{ scope.row.orderId || '--' }}</router-link>
              <span v-else>{{ scope.row.orderId || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="下单日期" width="110">
            <template slot-scope="scope">
              {{ scope.row.orderTime | standardFormatNoHour }}
            </template>
          </el-table-column>
          <el-table-column label="客户联系人" width="180">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.clientName" />
            </template>
          </el-table-column>
          <el-table-column label="账号" width="180">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.resourceName" />
            </template>
          </el-table-column>
          <el-table-column label="含税金额" width="100" align="right">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.taxAmount" :price="scope.row.taxAmount / 100" />
            </template>
          </el-table-column>
          <el-table-column label="品牌名称">
            <template slot-scope="scope">
              {{ scope.row.theme || '--' }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="tabIndex === 1 && selectOrders.length === 0">
        <empty-placeholder />
      </div>
      <div class="dialog-footer">
        <el-button size="small" type="primary" @click="handleOk">确定</el-button>
        <el-button class="cancel-btn-style" size="small" type="info" @click="closeDialog">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  standardFormat,
  standardFormatNoHour
} from '@/filters/date';
import Title from '@/components/Title';
import { getList } from '@/api/order';
import { moneyFilter } from '@/filters/number';
import { hasRouteAuth } from '@/utils/permission';
import ClearBtn from '@/components/Common/ClearBtn';
import ListTab from '@/components/ListTab';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import { numerical } from '@/utils/numFormat';
import mobileTable from '@/mixins/mobileTable';
export default {
  name: 'RelevanceOrderListDialog',
  components: { Title, ClearBtn, ListTab, EmptyPlaceholder },
  filters: {
    moneyFilter,
    standardFormat,
    standardFormatNoHour
  },
  mixins: [mobileTable],
  data() {
    return {
      loading: false,
      dialogVisible: false,
      // selectOrderIds: [],
      tabIndex: 0,
      tabs: [{
        'id': 0,
        'name': '订单列表',
        'num': 0
      }, {
        'id': 1,
        'name': '当前选中',
        'num': 0
      }],
      dateTime: '',
      selectOrders: [],
      originOrders: [], // 初始的订单id列表
      orderPage: 1,
      orderPerpage: 20,
      orderListLoading: false,
      queryForm: {
        orderId: '',
        dateEnd: '',
        dateStart: '',
        resourceName: '',
        taxAmount: '',
        terminalBrand: '',
        timeType: 0 // 下单时间类型
      },
      orderList: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInint: true
      }
    };
  },
  computed: {
    selectOrderIds() {
      const ids = this.selectOrders.map(res => {
        return res.id;
      });
      return ids;
    },
    allchecked() {
      var curTime = 0;
      this.orderList.items.forEach(item => {
        if (this.selectOrderIds.indexOf(item.id) >= 0) {
          curTime++;
        }
      });
      return curTime === this.orderList.items.length;
    },
    indeterminate() {
      var curTime = 0;
      this.orderList.items.forEach(item => {
        if (this.selectOrderIds.indexOf(item.id) >= 0) {
          curTime++;
        }
      });
      return curTime < this.orderList.items.length && curTime > 0;
    }
  },
  methods: {
    hasRouteAuth,
    keyupEvent(value) {
      const str = numerical(value, 3, 15);
      this.queryForm.taxAmount = str;
    },
    // 列表勾选相关
    renderHeader(h, { column, $index }) {
      return h('span', {}, [
        h('el-checkbox', {
          props: {
            value: this.allchecked,
            indeterminate: this.indeterminate
          },
          on: {
            change: this.updateAllSelected
          },
          style: {
            display: this.orderList.items.length > 0 ? 'block' : 'none'
          }
        })
      ]);
    },
    updateAllSelected(isCheck) {
      // const orderList = this.orderList.items;
      if (isCheck) {
        this.orderList.items.forEach(item => {
          if (this.selectOrderIds.indexOf(item.id) < 0) {
            this.selectOrders.push(item);
            this.tabs[1].num = this.selectOrders.length;
          }
        });
      } else {
        this.orderList.items.forEach(item => {
          const curIndex = this.selectOrderIds.indexOf(item.id);
          if (curIndex >= 0) {
            this.selectOrders.splice(curIndex, 1);
            this.tabs[1].num = this.selectOrders.length;
          }
        });
      }
    },
    // 是否选中
    isChecked(id) {
      return this.selectOrderIds.indexOf(id) >= 0;
    },
    //
    checkboxClick(isCheck, row) {
      const curIndex = this.selectOrderIds.indexOf(row.id);
      if (isCheck && curIndex < 0) {
        this.selectOrders.push(row);
        this.tabs[1].num = this.selectOrders.length;
      }
      if (!isCheck && curIndex >= 0) {
        this.selectOrders.splice(curIndex, 1);
        this.tabs[1].num = this.selectOrders.length;
      }
    },
    queryClick() {
      this.getOrderList(true);
    },
    queryEmpty() {
      this.dateTime = '';
      // this.queryForm.orderId = '';
      // this.queryForm.dateEnd = '';
      // this.queryForm.dateStart = '';
      // this.queryForm.resourceName = '';
      // this.queryForm.taxAmount = '';
      // this.queryForm.terminalBrand = '';
      const obj = this.queryForm;
      Object.keys(obj).forEach(i => { obj[i] = ''; });
      this.queryForm.timeType = 0;
      this.terminalBrand = '';
      this.getOrderList();
    },
    // 获取订单列表
    getOrderList(reset = false) {
      if (reset) this.orderPage = 1;
      this.orderListLoading = true;
      const params = { ...this.queryForm };
      params.taxAmount = params.taxAmount !== '' ? params.taxAmount * 100 : '';
      getList(this.orderPage, this.orderPerpage, params).then(res => {
        if (res.code === 200) {
          this.orderList = res.data;
        }
        this.orderListLoading = false;
      },
      result => {
        this.orderListLoading = false;
      });
    },
    // 通过订单id获取具体的订单信息
    getIdOrderList(ids) {
      const params = {
        ids: ids.join(',')
      };
      getList(1, ids.length, params).then(res => {
        if (res.code === 200) {
          this.selectOrders = res.data.items;
          this.tabs[1].num = res.data.items.length;
        }
      });
    },
    handleSizeChange(val) {
      this.orderPerpage = val;
      this.getOrderList(true);
    },
    handleCurrentChange(toPage) {
      this.orderPage = toPage;
      this.getOrderList();
    },
    handleClose() {
      this.dialogVisible = false;
    },
    handleOk() {
      const relatedOrderOptions = this.selectOrders.map(item => {
        return { id: item.id, orderId: item.orderId };
      });
      const relatedOrderIds = this.selectOrders.map(item => {
        return item.id;
      });
      const params = {
        relatedOrderOptions,
        relatedOrderIds
      };
      this.$emit('postMessage', params);
      this.dialogVisible = false;
    },
    datePickerTime(value) {
      if (!value) {
        this.queryForm.dateStart = '';
        this.queryForm.dateEnd = '';
      } else {
        this.queryForm.dateStart = value[0] / 1000;
        this.queryForm.dateEnd = value[1] / 1000;
      }
    },
    closeDialog() {
      this.dateTime = '';
      // this.queryForm.orderId = '';
      // this.queryForm.dateEnd = '';
      // this.queryForm.dateStart = '';
      // this.queryForm.resourceName = '';
      // this.queryForm.taxAmount = '';
      // this.queryForm.terminalBrand = '';
      const obj = this.queryForm;
      Object.keys(obj).forEach(i => { obj[i] = ''; });
      this.queryForm.timeType = 0;
      this.terminalBrand = '';
      this.originOrders = [];
      this.selectOrders = [];
      this.tabs[1].num = 0;
      this.tabIndex = 0;
      this.dialogVisible = false;
    },
    openDialog() {
    },
    opened() {
      if (this.originOrders.length > 0) this.getIdOrderList(this.originOrders);
      this.getOrderList(true);
    },
    initData(orders = []) {
      // console.log(orders);
      this.originOrders = orders;
    }
  }
};
</script>
<style lang="scss" scoped>
.relevance-order-common-dialog {
  .list-tab-relative {
    position: relative;
    height: 18px;
    .list-tab-absolute {
      position: absolute;
      top: -46px;
      left: 50%;
      transform: translateX(-30%);
      display: flex;
      justify-content: center;
      width: 300px;
    }
  }
  .table-box {
    max-height: 372px;
    overflow: auto;
  }
  .pagination-area {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    .el-pagination {
      display: flex;
      justify-content: center;
    }
    & ::v-deep {
      .el-input__inner {
        width: 100%;
      }
    }
  }
  & ::v-deep {
    .dialog-footer {
      margin-top: 22px;
    }
    .el-form--inline .el-form-item {
      margin-right: 32px !important;
    }
    .el-table::before {
      height: 0;
    }
    .el-table__body .el-table__row:last-child td {
      border-bottom: 1px solid #EBEEF5;
    }
    .el-date-editor--daterange.el-input__inner {
      width: 240px;
    }
  }
  .original-order {
    &:hover {
      color: #406EFF;
    }
  }
  .relevance-pagination {
    ::v-deep .el-input__inner {
      width: unset;
    }
  }
  .mobile-el-form {
    ::v-deep .el-input__inner {
      width: 100%;
    }
  }
  &.relevance-order-mobile-dialog {
    .list-tab-relative {
      height: 32px;
      .list-tab-absolute {
        top: -24px;
      }
    }
    .query-button {
      margin-bottom: 8px;
    }
  }
}
</style>
<style lang="scss">
.relevance-order-common-dialog {
  // .el-dialog {
  //   width: unset !important;
  // }
  .el-dialog__body {
    padding: 32px;
  }
  .el-form {
    padding-left: 10px;
  }
  .total-table-list {
    .el-table {
      width: 99.9%;
    }
  }
}
</style>
